// mycomponent/temp/qrcode/qrcode.js
var app = getApp();
import drawQrcode from "../../../../utils/weapp.qrcode.esm.js";
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    isshow: {
      value: false,
      type: Boolean,
    },
    showcarrfootBol: {
      type: null,
    },
    iPnoneBottomBol: {
      type: null,
    },
    kid: {
      type: null,
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    errorFlag: false,
    errorMsg: "",
    poster: "",
    poster_id: 0,
    loading: 0,
    getFlag: true,
    step: 1.5,
    is_id: "",
  },
  ready() {
    //	this.getPosterPic();
  },
  observers: {
    isshow: function (isshow) {
      let that = this;
      if (isshow && this.data.poster == "" && this.data.getFlag) {
        this.getPosterPic();
        this.data.getFlag = false;
      }
      that.setData({
        is_id: this.data.kid,
      });
    },
  },
  /**
   * 组件的方法列表
   */
  methods: {
    loadImgError(err) {
      this.setData({
        errorFlag: true,
        errorMsg: err.detail.errMsg,
      });
    },
    // 隐藏二维码
    clicktapshow() {
      this.setData({
        isshow: false,
      });
      this.triggerEvent("myshow", this.data.isshow);
      // wx.showTabBar({})
    },
    previewImage() {
      wx.showToast({
        title: "长按分享好友",
        icon: "none",
        duration: 1800,
      });
      wx.previewImage({
        urls: [this.data.poster], // 当前显示图片的链接
      });
    },
    async getPosterPic() {
      let posterSize = await this.getMyCanvasMessage(640, 1008);

      var urlStr = app.getNetAddresss(
        "plugin.skin-check.api.skin-check.poster"
      );
      this.setData({
        canvasWidth: posterSize.width,
        canvasHeight: posterSize.height,
      });
      //this.startDrawCanvas(posterSize,{});
      app._getNetWork({
        showToastIn: false,
        url: urlStr,
        data: {
          report_id: this.data.is_id,
          ingress: "weChatApplet",
        },
        success: (resdata) => {
          let res = resdata.data;
          if (res.result != 1) {
            return;
          }
          // if(res.data.center_show==0){
          // 	this.setData({
          // 		loading:100,
          // 		poster: res.data.image_url,
          // 	});
          // }else if(res.data.center_show==1){
          this.data.poster_id = resdata.data.data.id;
          this.startDrawCanvas(posterSize, res.data);
        },
      });
    },
    getPosterTp2() {
      let that = this;
      let urlStr = app.getNetAddresss("member.poster");
      app._getNetWork({
        url: urlStr,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            if (res.data.image_url == "" || res.data.image_url == null) {
              wx.showToast({
                title: "请稍等" + res.data.image_url,
                icon: "none",
                duration: 2000,
              });
              setTimeout(() => {
                this.getPosterTp2();
              }, 500);
            } else if (res.data.image_url != "") {
              setTimeout(() => {
                that.setData({
                  poster: res.data.image_url,
                });
              }, 1000);
            }
          } else {
            wx.showToast({
              title: res.msg,
              icon: "none",
              duration: 1500,
            });
          }
        },
        fail: function (res) {
          if (this.data.timer) {
            clearInterval(this.data.timer);
          }
          wx.hideLoading({});
          console.log(res);
        },
      });
    },

    //工具
    //开始绘制
    async startDrawCanvas(posterSize, posterData) {
      const ctx = wx.createCanvasContext("myCanvas", this);
      // this.drawRoundRectPath(ctx,posterSize.width,posterSize.height,30);
      ctx.setFillStyle("#fff");
      ctx.fillRect(0, 0, posterSize.width, posterSize.height);
      //ctx.draw();
      //下载背景
      let bgImg = await this.readDownPicInfo(posterData.background);
      //绘制背景图片
      if (bgImg.height > bgImg.width) {
        let p = posterSize.height / posterSize.contentScale / bgImg.height;
        bgImg.height = bgImg.height * p;
        bgImg.width = bgImg.width * p;
      } else {
        let p = posterSize.width / posterSize.contentScale / bgImg.width;
        bgImg.width = bgImg.width * p;
        bgImg.height = bgImg.height * p;
      }
      this.drawCanvasImage(ctx, {
        left: 0,
        top: 0,
        width: bgImg.width / this.data.step,
        height: bgImg.height / this.data.step,
        img: bgImg.img,
        contentScale: posterSize.contentScale,
      });
      this.setData({ loading: 10 });

      //绘制其他内容
      let otherData = posterData.style_data;
      for (let i = 0; i < otherData.length; i++) {
        let item = otherData[i];
        //绘制昵称
        item.contentScale = posterSize.contentScale;
        console.log(item);
        if (item.type == "nickname") {
          item.contentScale = item.contentScale * 2;
          this.drawCanvasText(ctx, item);
        } else if (item.type == "logo" || item.type == "avatar") {
          // 代表后台有图片
          // //下载和读取图片
          let file = await this.readDownPicInfo(item.src);
          item.img = file.img;
          item.contentScale = item.contentScale * 2;
          console.log("111111111", item);
          this.drawCanvasImage(ctx, item);
        } else if (item.type == "qr") {
          //小程序二维码
          let file = await this.readDownPicInfo(item.src);
          item.img = file.img;
          item.contentScale = item.contentScale * 2;
          this.drawCanvasImage(ctx, item);
        } else if (item.type == "score") {
          item.contentScale = item.contentScale * 2;
          let step = this.data.step;
          let Dx = item.left * item.contentScale * step + item.width / 2;
          let Dy = item.top * item.contentScale * step + item.height / 2;
          this.drawArc(item.src, Dx, Dy, ctx, item);
        } else if (item.type == "result") {
          console.log(item);
          item.contentScale = item.contentScale * 2;
          this.drawEnd(ctx, item);
        }
        let loading = parseInt((80 / otherData.length) * (i + 1));
        this.setData({ loading: loading + 10 });
      }
      console.log("执行完成");
      ctx.draw(
        false,
        setTimeout(async () => {
          let img = await this.toimage("myCanvas", posterSize);
          this.setData({
            loading: 100,
            poster: img,
          });
          this.upQrcodeImg(img);
        }, 1000)
      );
    },
    //矩形
    drawEnd(ctx, Info) {
      let that = this;
      let step = that.data.step;
      let Dx = Info.left * Info.contentScale * step;
      let Dy = Info.top * Info.contentScale * step;
      let height = Info.height / 3;
      that.roundRect(
        ctx,
        Dx,
        Dy,
        Info.width,
        height,
        10,
        Info.color,
        Info.src[0],
        Info
      );
      that.roundRect(
        ctx,
        Dx,
        Dy + (height + 10),
        Info.width,
        height,
        10,
        Info.color,
        Info.src[1],
        Info
      );
      if(Info.src[2]){
        that.roundRect(
          ctx,
          Dx,
          Dy + (height + 10 + height + 10),
          Info.width,
          height,
          10,
          Info.color,
          Info.src[2],
          Info
        );
      }

    },

    roundRect(ctx, x, y, w, h, r, c, txt, info) {
      if (w < 2 * r) {
        r = w / 2;
      }
      if (h < 2 * r) {
        r = h / 2;
      }

      ctx.beginPath();
      ctx.fillStyle = c;

      ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5);
      ctx.moveTo(x + r, y);
      ctx.lineTo(x + w - r, y);
      ctx.lineTo(x + w, y + r);

      ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2);
      ctx.lineTo(x + w, y + h - r);
      ctx.lineTo(x + w - r, y + h);

      ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5);
      ctx.lineTo(x + r, y + h);
      ctx.lineTo(x, y + h - r);

      ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI);
      ctx.lineTo(x, y + r);
      ctx.lineTo(x + r, y);

      ctx.fill();
      ctx.closePath();
      ctx.beginPath();
      ctx.setFontSize(20); // 字体大小 注意不要加引号
      ctx.setFillStyle(info.font_color); // 字体颜色
      // ctx.setTextAlign("center");	 // 字体位置
      ctx.setTextBaseline("middle"); // 字体对齐方式
      console.log(x, y);
      ctx.fillText(
        `${txt.target.target_name}:${txt.value_desc?txt.value_desc:txt.value}`,
        x + w / 2,
        y + h / 2
      ); // 文字内容和文字坐标
      ctx.restore();
    },
    // 圆弧
    drawArc(c, w, h, ctx, Info) {
      // 白色外圈
      let step = this.data.step;
      let Dx = Info.left * Info.contentScale * step + Info.width / 2;
      let Dy = Info.top * Info.contentScale * step + Info.height / 2;
      ctx.arc(Dx, Dy, Info.width / 2, 0, 2 * Math.PI);
      ctx.setStrokeStyle("#f8f8f8"); //圆环线条的颜色
      ctx.setLineWidth("12"); //圆环的粗细
      ctx.setLineCap("round"); //圆环结束断点的样式  butt为平直边缘 round为圆形线帽  square为正方形线帽
      ctx.stroke();
      ctx.closePath();
      ctx.restore();
      ctx.save();
      // 开始绘制百分比数字
      ctx.beginPath();
      ctx.setFontSize(40); // 字体大小 注意不要加引号
      ctx.setFillStyle("#ff5000"); // 字体颜色
      ctx.setTextAlign("center"); // 字体位置
      ctx.setTextBaseline("middle"); // 字体对齐方式
      ctx.fillText(c, w - 10, h); // 文字内容和文字坐标
      ctx.restore();
      // 绘制文字
      ctx.beginPath();
      ctx.setFontSize(24); // 字体大小 注意不要加引号
      ctx.setFillStyle("#ff5000"); // 字体颜色
      ctx.setTextAlign("center"); // 字体位置
      ctx.setTextBaseline("middle"); // 字体对齐方式
      ctx.fillText("分", w + 24, h - 10); // 文字内容和文字坐标
      ctx.restore();
      var num = ((2 * Math.PI) / 100) * c - 0.5 * Math.PI;
      //蓝色圆环的绘制
      ctx.arc(w, h, Info.width / 2, -0.5 * Math.PI, num); //绘制的动作
      ctx.setStrokeStyle(Info.color); //圆环线条的颜色
      ctx.setLineWidth("12"); //圆环的粗细
      ctx.setLineCap("round"); //圆环结束断点的样式  butt为平直边缘 round为圆形线帽  square为正方形线帽
      ctx.stroke();
      ctx.beginPath();
    },

    //绘制图片
    drawCanvasImage(ctx, imgInfo) {
      let step = this.data.step;
      console.log("左上角 x 坐标", imgInfo.left * imgInfo.contentScale * step);
      console.log("左上角 y 坐标", imgInfo.top * imgInfo.contentScale * step);
      ctx.drawImage(
        imgInfo.img,
        imgInfo.left * imgInfo.contentScale * step,
        imgInfo.top * imgInfo.contentScale * step,
        imgInfo.width * imgInfo.contentScale * step,
        imgInfo.height * imgInfo.contentScale * step
      ); // 推进去图片
    },
    //绘制文字
    drawCanvasText(ctx, textInfo) {
      let step = this.data.step;
      console.log(step);
      console.log(textInfo);
      let size = textInfo.font_size * textInfo.contentScale;
      let top = textInfo.top * textInfo.contentScale + size;
      console.log(size, top * step);
      ctx.setFontSize(size * step);
      ctx.setFillStyle(textInfo.color);
      ctx.fillText(
        textInfo.src,
        textInfo.left * textInfo.contentScale * step,
        textInfo.top * textInfo.contentScale * step + size * 2
      );
      console.log("完成");
    },
    //导出图片
    toimage(canvasId, posterSize) {
      return new Promise((resolve, reject) => {
        console.log(canvasId, posterSize);
        wx.canvasToTempFilePath(
          {
            x: 0,
            y: 0,
            //	quality:1,
            width: posterSize.width,
            height: posterSize.height,
            destWidth: posterSize.width * 4,
            destHeight: posterSize.height * 4,
            canvasId: canvasId,
            success: (res) => {
              var tempFilePath = res.tempFilePath;
              resolve(tempFilePath);
            },
            fail: (res) => {
              wx.showToast({
                title: "图片导出失败" + res,
                icon: "success",
                duration: 2000,
              });
            },
          },
          this
        );
      });
    },
    drawRoundRectPath(ctx, width, height, radius) {
      ctx.beginPath(0);
      //从右下角顺时针绘制，弧度从0到1/2PI
      ctx.arc(width - radius, height - radius, radius, 0, Math.PI / 2);
      //矩形下边线
      ctx.lineTo(radius, height);
      //左下角圆弧，弧度从1/2PI到PI
      ctx.arc(radius, height - radius, radius, Math.PI / 2, Math.PI);
      //矩形左边线
      ctx.lineTo(0, radius);
      //左上角圆弧，弧度从PI到3/2PI
      ctx.arc(radius, radius, radius, Math.PI, (Math.PI * 3) / 2);
      //上边线
      ctx.lineTo(width - radius, 0);
      //右上角圆弧
      ctx.arc(width - radius, radius, radius, (Math.PI * 3) / 2, Math.PI * 2);
      //右边线
      ctx.lineTo(width, height - radius);
      ctx.closePath();
      ctx.clip();
    },
    //下载和读取图片
    readDownPicInfo(url) {
      console.log(url);
      return new Promise((resolve, reject) => {
        wx.downloadFile({
          url, //仅为示例，并非真实的资源
          success: (res) => {
            wx.getImageInfo({
              src: res.tempFilePath,
              success(res1) {
                //确保是一张图片
                resolve({
                  img: res.tempFilePath,
                  width: res1.width,
                  height: res1.height,
                });
              },
              fail: (err) => {
                this.data.getFlag = true;
                console.log("图片读取出错", err.errMsg);
                wx.showToast({
                  title: "图片读取出错" + err.errMsg,
                  icon: "success",
                  duration: 2000,
                });
              },
            });
          },
          fail: (res) => {
            this.data.getFlag = true;
            console.log("图片下载出错", res);
            wx.showToast({
              title: "图片下载出错" + res,
              icon: "none",
              duration: 2000,
            });
          },
        });
      });
    },
    // 获取海报画布宽高
    getMyCanvasMessage(w, h) {
      return new Promise((resolve, reject) => {
        wx.getSystemInfo({
          success: (res) => {
            let scale = h / w;
            let width = res.screenWidth - res.screenWidth * 0.2;
            let height = width * scale;
            let contentScale = width / w;
            (width = width * this.data.step),
            (height = height * this.data.step);
            resolve({
              width,
              height,
              contentScale,
            });
          },
          fail: (res) => {
            this.data.getFlag = true;
          },
        });
      });
    },
    getQRCodeUrl(item) {
      return new Promise((resolve, reject) => {
        let step = this.data.step;
        this.setData(
          {
            tempQRCodeCanvasWidth: item.width * item.contentScale * step,
            tempQRCodeCanvasHeight: item.height * item.contentScale * step,
          },
          async () => {
            drawQrcode({
              width: (item.width * item.contentScale - 10) * step,
              height: (item.height * item.contentScale - 10) * step,
              canvasId: "tempQRCode",
              background: "#fff",
              _this: this,
              x: 5 * step,
              y: 5 * step,
              text: item.src,
              callback: () => {
                setTimeout(async () => {
                  let img = await this.toimage("tempQRCode", {
                    width: item.width * item.contentScale * step,
                    height: item.height * item.contentScale * step,
                  });
                  resolve(img);
                }, 500);
              },
            });
          }
        );
      });
    },
    pxToNum(px) {
      let num = px.substring(0, px.length - 2);
      return parseInt(num);
    },
    upQrcodeImg(imgFile) {
      let urlStr = app.getNetAddresss("upload.uploadPic");
      console.log(imgFile);
      wx.uploadFile({
        url: urlStr,
        filePath: imgFile,
        name: "file",
        header: { "Content-Type": "multipart/form-data" },
        formData: {
          // 和服务器约定的token, 一般也可以放在header中
          _wx_token: wx.getStorageSync("wx_token"),
          ingress: 0,
        },
        success: (res) => {
          let data = JSON.parse(res.data);
          console.log("上传成功", data);
          if (data.result == 1) {
            //data.data.img_url
            console.log(data.data.img_url);
            // this.addPosterRecord(data.data.img_url);
          }
        },
        fail: function (e) {
          console.log("上传失败一一一", e);
        },
      });
    },
    addPosterRecord(img_url) {
      var urlStr = app.getNetAddresss("member.qrcode.poster-record");
      console.log("开始写记录");
      app._getNetWork({
        showToastIn: false,
        url: urlStr,
        data: {
          image: img_url,
          poster_id: this.data.poster_id,
        },
        success: (resdata) => {},
      });
    },
    async checkWritePotosAlbum() {
      var _this = this;
      let writePhotosAlbum = await this.getAuthSetting(
        "scope.writePhotosAlbum"
      );
      if (!writePhotosAlbum) {
        wx.showModal({
          title: "请开启授权",
          content: "是否跳转设置页开启授权",
          success(res) {
            if (res.confirm) {
              wx.openSetting({
                success(settingdata) {
                  if (settingdata.authSetting["scope.writePhotosAlbum"]) {
                    _this.saveImg();
                  } else {
                    console.log("还是没授权");
                  }
                },
              });
            } else if (res.cancel) {
              console.log("用户点击取消");
            }
          },
        });
        return;
      }
      this.saveImg();
    },
    saveImg() {
      console.log("执行");
      var imgSrc = this.data.poster;
      wx.downloadFile({
        url: imgSrc,
        success: function (res) {
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: (data) => {
              wx.showToast({
                title: "保存成功",
                icon: "none",
                duration: 2000,
              });
            },
            fail: function (err) {
              wx.showToast({
                title: err.msg,
                icon: "none",
                duration: 1000,
              });
              console.log(err);
            },
          });
        },
      });
    },
    getAuthSetting(authName) {
      return new Promise((resolve, reject) => {
        wx.getSetting({
          success(res) {
            if (!res.authSetting[authName]) {
              wx.authorize({
                scope: authName,
                success() {
                  resolve(true);
                },
                fail() {
                  resolve(false);
                },
              });
            } else resolve(true);
          },
          fail() {
            resolve(false);
          },
        });
      });
    },
  },
});
